package com.ncmem.up6.store.minio;

import com.ncmem.up6.utils.PathTool;
import com.ncmem.up6.model.FileInf;
import com.ncmem.up6.store.FileBlockWriter;
import com.ncmem.up6.store.StorageType;
import org.apache.commons.lang.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class MinioWriter extends FileBlockWriter {

    public MinioWriter() {
        this.storage= StorageType.Minio;
    }

    /**
     * 生成UploadId
     */
    public String make(FileInf file) throws IOException {
        String ext = PathTool.getExtention(file.pathSvr);
        byte[] buf = new byte[0];
        String fileID = MinioTool.CreateMultipartUpload(file.S3Key());
        if(StringUtils.isEmpty(fileID)) throw new IOException("minio CreateMultipartUpload error");
        return fileID;
    }

    public String write(FileInf file, ByteArrayOutputStream ostm) throws IOException {
        byte[] data = ostm.toByteArray();
        file.etag = MinioTool.UploadPart(file.S3Key(), file.blockIndex, file.object_id, data);
        file.saveEtags();
        if (StringUtils.isEmpty(file.etag)) throw new IOException("minio upload part error");
        return file.etag;
    }

    /**
     * 写入最后一块数据=>所有文件块上传完毕
     * @param file
     * @return
     */
    public boolean writeLastPart(FileInf file) throws IOException {
        boolean v = MinioTool.CompleteMultipartUpload(file);
        if(!v) throw new IOException("Minio CompleteMultipartUpload error");
        return v;
    }
}
